package com.hedl.practice.diyJava.io.study_writer.test;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        String encoding = "UTF-8";
        File file = new File("/Users/a101/idea/untitled folder/like.txt");
        try(Writer w = new FileWriter("/Users/a101/idea/untitled folder/like.txt", StandardCharsets.UTF_8)){
            w.write("你好；\n");
            w.write("  我是小明，很高兴见到你；\n");
            w.write("你好小明，我是Writer;");
        }

        /**
         * 读取出来，方式一
         */
        /*try(InputStreamReader input = new InputStreamReader(new FileInputStream(file),encoding)){
            BufferedReader bufferedReader = new BufferedReader(input);
            String line;
            while((line = bufferedReader.readLine())!= null){
                System.out.println(line);
            }
        }*/

        //方式二
        /*try(Reader r = new FileReader("/Users/a101/idea/untitled folder/like.txt",StandardCharsets.UTF_8)){
            StringBuilder sb = new StringBuilder();
            int like;
            while((like = r.read()) != -1){
                sb.append((char) like);
            }
            System.out.println(sb.toString());
        }*/

        //方式三
        try {
            File files = new File("/Users/a101/idea/untitled folder/like.txt"); // 指定文件名
            Scanner scanner = new Scanner(files); // 获取文件扫描器对象
            while (scanner.hasNextLine()) { // 判断是否还有下一行
                String line = scanner.nextLine(); // 获取下一行内容
                System.out.println(line); // 打印每行内容
            }
            scanner.close(); // 关闭扫描器
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        System.out.println("==============================CharArrayWriter===============================");
        /**
         * CharArrayWriter和ByteArrayOutputStream是一样的
         */
        try(CharArrayWriter writer = new CharArrayWriter()){
            writer.write(65);
            writer.write(66);
            writer.write(67);
            char[] chars = writer.toCharArray();
            System.out.println(chars);
        }

        System.out.println("================================StringWriter=================================");
        /**
         * StringWriter也是一个基于内存的Writer，它和CharArrayWriter类似。
         * 实际上，StringWriter在内部维护了一个StringBuffer，并对外提供了Writer接口
         */

        System.out.println("================================OutputStreamWriter==========================");

    }
}
